package com.gnerv.plug.comment.action;

import com.gnerv.plug.commom.FreeMarkerUtils;
import com.gnerv.plug.constant.EmbraceSourceInfo;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;

import javax.swing.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ClassCommentAction extends AnAction {

    private static final Pattern PATTERN = Pattern.compile("(\\n@\\S|public class)+");

    public ClassCommentAction() {
        super();
    }
    public ClassCommentAction(String text, String description, Icon icon) {
        super(text, description, icon);
    }

    @Override
    public void actionPerformed(AnActionEvent event) {
        final Editor editor = event.getRequiredData(CommonDataKeys.EDITOR);
        final Project project = event.getRequiredData(CommonDataKeys.PROJECT);
        final Document document = editor.getDocument();

        Map commentInfo = getCommentInfo();
        String description = FreeMarkerUtils.getContent("CommentClass.ftl", commentInfo);
        Matcher matcher = PATTERN.matcher(document.getText());
        if (matcher.find()) {
            int start = matcher.start();
            WriteCommandAction.runWriteCommandAction(project, () ->
                    document.insertString(start - 1, description)
            );
        }
    }

    private Map getCommentInfo(){
        Map map = new HashMap(8);
        String description = Messages.showInputDialog(EmbraceSourceInfo.NAME, "Class Comment", Messages.getQuestionIcon());
        map.put("description", description);
        PropertiesComponent instance = PropertiesComponent.getInstance();
        String author = instance.getValue(EmbraceSourceInfo.COMMENT_AUTHOR);
        map.put("author", author);
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String createDate = today.format(formatters);
        map.put("createDate", createDate);
        return map;
    }

}
